package com.gree.flowable.app.controller;

import com.gree.common.flowable.ex.ApplySubmitPO;
import com.gree.common.utils.RedisUtil;
import com.gree.flowable.app.pojo.ex.StartPiExIForm;
import com.gree.flowable.app.pojo.form.CreateTables;
import com.gree.flowable.app.pojo.form.IFormDataVO;
import com.gree.flowable.app.pojo.model.StartProcessInstanceMO;
import com.gree.flowable.app.pojo.vo.ReturnVO;
import com.gree.flowable.app.services.ICreateTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ：180849
 * @date ：Created in 2021/4/27 9:19
 * @description：创建数据表
 * @modified By：
 * @version: 1.0
 */

@RestController
@RequestMapping("/rest/table")
public class ICreateTableApi {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICreateTableService iCreateTableService;

    @PostMapping("/create/{tableName}")
    public ReturnVO createTables(@PathVariable String tableName, @RequestBody List<CreateTables> columnList){
        return iCreateTableService.createTable(tableName, columnList);
    }

    @GetMapping("/columns/{formId}")
    public ReturnVO queryTableColumns(@PathVariable String formId){
        return iCreateTableService.queryTableColumns(formId);
    }

    /**
     * 开始流程 加上申请单信息
     * 定制化内容太多。后期运维成本将是一个未知数
     */
    @PostMapping("/start")
    public ReturnVO whatShouldIDo(@RequestBody StartPiExIForm params){
        // 该方法慎修改！
        return iCreateTableService.youCanDoIt(params);
    }

    @PostMapping("/sumbit")
    public ReturnVO whatShouldIDo(@RequestBody ApplySubmitPO params){
        String processKey = params.getProcessDefinitionKey();
        StartProcessInstanceMO startProcessInstanceMO = new StartProcessInstanceMO();
        startProcessInstanceMO.setProcessDefinitionKey(processKey);
        startProcessInstanceMO.setFormName(params.getFormName());
        startProcessInstanceMO.setCurrentUserCode(params.getUserId());
        double hincr = redisUtil.hincr("flowable", processKey, 1);
        int sequ = (int) hincr;
        String id;
        for (id = (new StringBuilder(String.valueOf(sequ))).toString();
             id.length() < 8; ) {
            id = (new StringBuilder("0")).append(id).toString();
        }
        id = (new StringBuilder(String.valueOf(processKey))).append(id).toString();
        startProcessInstanceMO.setBusinessKey(id);

        IFormDataVO iFormDataVO = new IFormDataVO(id, params.getFormId(), params.getData());
        StartPiExIForm startPiExIForm = new StartPiExIForm();
        startPiExIForm.setStartProcessInstanceMO(startProcessInstanceMO);
        startPiExIForm.setiFormDataVO(iFormDataVO);

        return iCreateTableService.youCanDoIt(startPiExIForm);
    }
}
